from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response

from user.models import Address
from .serializer import AreaSerializer, AddressSerializer
from .models import Area
from rest_framework_extensions.cache.mixins import CacheResponseMixin



# Create your views here.

class AreasView(CacheResponseMixin, ListAPIView):
    serializer_class = AreaSerializer
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin, ListAPIView):
    serializer_class = AreaSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


# post address/  新增收货地址
class AddressView(CreateAPIView, ListAPIView):
    serializer_class = AddressSerializer

    # queryset = Address.objects.filter(is_deleted=False)
    def get_queryset(self):
        return Address.objects.filter(is_deleted=False, user=self.request.user)

    # def get_queryset(self):
    #     # 通过序列化器查询数据
    #     return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        serializer = AddressSerializer(self.get_queryset(), many=True)
        user = self.request.user
        constants = 10
        return Response({
            'addresses': serializer.data,
            'limit': constants,
            'default_address_id': user.default_address_id,
        })
